﻿if (!InfoSource) var InfoSource = {};

InfoSource.Pages = {};
InfoSource.PageWidth = $(window).width() * .99;
InfoSource.PageHeight = $(window).height() * .99;
InfoSource.ExternalLoadedScripts = {};

InfoSource.Init = function () {
	this.InitHandlers();
	this.InitOptionsMenu();
	this.SetPageCollection();

	$("#content").width(InfoSource.PageWidth * 2.1);
	$(".pageContent")
		.addClass("active")
		.width(InfoSource.PageWidth);


}

/*---------------------------------------------------------------------------*/
InfoSource.InitHandlers = function () {
	$("#btnOptionsMenu").on("click",
		function (e) {
			InfoSource.ShowOptionsMenu();
			e.stopPropagation();
		}
	);


	/*--------------------*/
	$("body, #OptionsMenu").on("click",
		function (e) {
			InfoSource.HideOptionsMenu();
		}
	);

	/*--------------------*/
	$("body").on("click", "a[handledlink]",
		function (e) {
			InfoSource.handledLinkClick(this);
			return false;
		}
	);



}

/*---------------------------------------------------------------------------*/
InfoSource.SetPageCollection = function () {
	var currentPages = $(".pageContent");
	for (var x = 0; x < currentPages.length; x++) {
		var currentPage = $(currentPages[x]);
		var key = currentPage.attr("key");

		InfoSource.Pages[key] = currentPage;
	}
}

/*---------------------------------------------------------------------------*/
InfoSource.ShowOptionsMenu = function() {
	$("#OptionsMenu").slideDown(100);
}

/*---------------------------------------------------------------------------*/
InfoSource.HideOptionsMenu = function () {
	var menu = $("#OptionsMenu");
	menu.menu("collapseAll", null, true);
	$("#OptionsMenu").slideUp(100);
}

/*---------------------------------------------------------------------------*/
InfoSource.InitOptionsMenu = function () {
	var $optionsMenu = $("#OptionsMenu");

	$optionsMenu.menu();
	$optionsMenu.position(
		{
			my: "right top",
			at: "right bottom",
			of: $("#btnOptionsMenu")
		}
	);
}

/*---------------------------------------------------------------------------*/
InfoSource.handledLinkClick = function (elLink) {

	var $link = $(elLink);
	var handledlink = $link.attr("handledlink");

	if (handledlink != false) {
		var linktype = $link.attr("linktype");
		var href = $link.attr("href") || "";

		var $showDeferred = $.Deferred();
		$showDeferred.done(function () {
			switch (linktype) {
				case "page":
					InfoSource.ShowPage(href, linktype);
					$("#navigation-tabs li.selected").removeClass("selected");
					break;

				case "tab":
					InfoSource.ShowPage(href, linktype);
					$("#navigation-tabs li.selected").removeClass("selected");
					$link.closest("li").addClass("selected");
					break;

				case "popup":
					InfoSource.ShowPopUp(href);
					break;
			}
		});



		if (!InfoSource.Pages[href]) {
			InfoSource.LoadPage(href, linktype, $showDeferred);
		}
		else {
			$showDeferred.resolve();
		}


	}

}

/*---------------------------------------------------------------------------*/
InfoSource.LoadPage = function (href, linktype, $showDeferred /*optional*/) {
    $.ajax(
			{
			    url: href,
			    dataType: "json",
			    type: "POST",
			    data: { "viewtype": "partial" }
			}
	).done(
		function (data) {
		    switch (linktype) {
		        case "page":
		            InfoSource.RenderPage(data.html || "", href);
		            break;

		        case "tab":
		            InfoSource.RenderPage(data.html || "", href);
		            break;

		        case "popup":
		            InfoSource.RenderPopUp(data.html || "", href);
		            break;
		    }

		    InfoSource.RenderStyleSheets(data.styleSheets);
		    InfoSource.RenderScripts(data.scripts)
				.done(function () { InfoSource.RenderInlineScripts(data.inlineScripts); });

		    if ($showDeferred)
		        $showDeferred.resolve();
		}
	)
    .fail(function (a, b, c) {
            console.log(a); console.log(b); console.log(c);
        }
    );
}

/*---------------------------------------------------------------------------*/
InfoSource.RenderPopUp = function (html, href) {
    var $html = $("<div>" + html + "</div>");

    $("body").append($html);
    $html.css("display", "none");

    InfoSource.Pages[href] = $html;
}

/*---------------------------------------------------------------------------*/
InfoSource.RenderPage = function (html, href) {

	var $newPage = $(html);
	var $currentPage = $(".pageContent.active");

	$newPage.css({ "width": (InfoSource.PageWidth), "height": (InfoSource.PageHeight - 117) });
	$("#content").append($newPage);


	InfoSource.Pages[href] = $newPage;

}

/*---------------------------------------------------------------------------*/
InfoSource.RenderScripts = function (scripts) {
	var existingScripts = $("script");
	var $scriptDeferred = $.Deferred();
	var scriptLoadCount = 0;

	for (var x = 0; x < scripts.length; x++) {
		var currentScript = scripts[x];
		var foundInScripts = false;
		var foundInExternalLoadedScripts = false;

		for (var y = 0; y < existingScripts.length; y++) {
			var currentExistingScript = existingScripts[y].src;

			if (currentExistingScript.indexOf(currentScript) > -1) {
				foundInScripts = true;
				scriptLoadCount++;
				break;
			}
		}

		if (!foundInScripts) {
			if (InfoSource.ExternalLoadedScripts[currentScript]) {
				foundInExternalLoadedScripts = true;
				scriptLoadCount++;
			}
		}

		if (!foundInExternalLoadedScripts && !foundInScripts) {		
			LazyLoad.js(currentScript, function () {
				scriptLoadCount++;
				if (scriptLoadCount == scripts.length) 
					$scriptDeferred.resolve();
				InfoSource.ExternalLoadedScripts[currentScript] = true;
			});
		}
	}

	return $scriptDeferred;
}

/*---------------------------------------------------------------------------*/
InfoSource.RenderInlineScripts = function (inlineScripts) {
	$inlineDeferred = $.Deferred();

	eval(inlineScripts.join(";"));
	//$("body").append("<script type='text/javascript'>" + inlineScripts.join("") + "</scripts>");
	/*
	var newScript = document.createElement("script");
	
	newScript.type = "text/javascript";

	newScript.innerHTML = inlineScripts.join(";\n");
	$("body").append(newScript);
	$(newScript).on("load", function () { eval($(this).text()); $inlineDeferred.resolve(); });
	*/
	return $inlineDeferred;
}

/*---------------------------------------------------------------------------*/
InfoSource.RenderStyleSheets = function (styleSheets) {
	var existingStyleSheets = $("link[rel=stylesheet]");
	var $styleSheetDeferred = $.Deferred();
	var styleSheetLoadCount = 0;

	for (var x = 0; x < styleSheets.length; x++) {
		var currentStyleSheet = styleSheets[x];
		var foundInStyleSheets = false;

		for (var y = 0; y < existingStyleSheets.length; y++) {
			var currentExistingStyleSheet = existingStyleSheets[y].href;

			if (currentExistingStyleSheet.indexOf(currentStyleSheet) > -1) {
				foundInStyleSheets = true;
				styleSheetLoadCount++;
				break;
			}
		}


		if (!foundInStyleSheets) {

			LazyLoad.css(currentStyleSheet, function () {
				styleSheetLoadCount++;
				if (styleSheetLoadCount == styleSheets.length) $styleSheetDeferred.resolve();				
			});

		}
	}

	return $styleSheetDeferred;
}

/*---------------------------------------------------------------------------*/
InfoSource.ShowPage = function (href) {
	var $newPage = InfoSource.Pages[href];
	if (typeof $newPage === "undefinded") return;

	var $currentActivePage = $(".pageContent.active");

	$currentActivePage.toggle("slide",{direction:"left"}, 500, function () { $currentActivePage.removeClass("active"); });
	$newPage.toggle("slide",{direction:"right"}, 500, function () { $newPage.addClass("active"); });

}

/*---------------------------------------------------------------------------*/
InfoSource.ShowPopUp = function (href) {
	if (typeof InfoSource.Pages[href] == "undefined") return;

	var $html = InfoSource.Pages[href];
	var $title = $html.find(".pageTitle");
	var title = $title.text();

	$title.hide();
	$html.find(".pageContent").show();

	$($html).dialog(
		{
			width: ($("body").width() * .9),
			height: ($(window).height() * .9),
			modal: true,
			title: (title || "")
		}
	);
};

/*---------------------------------------------------------------------------*/
InfoSource.ShowLoading = function (selector) {
	var jEl = $(selector);
	jEl.append("<div class='generic-loading '></div>");
};

/*---------------------------------------------------------------------------*/
InfoSource.GoogleMapLatlngToPoint = function (map, latlng) {
	var topRight = map.getProjection().fromLatLngToPoint(map.getBounds().getNorthEast());
	var bottomLeft = map.getProjection().fromLatLngToPoint(map.getBounds().getSouthWest());
	var scale = Math.pow(2, map.getZoom());
	var worldPoint = map.getProjection().fromLatLngToPoint(latlng);
	var point = new google.maps.Point((worldPoint.x - bottomLeft.x) * scale, (worldPoint.y - topRight.y) * scale);

	return point;
};

/*=======================================================================*/
$(document).on("ready", function () { InfoSource.Init(); });  